package zz.test.bluetoothdemo;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Locale;

/**
 * Created by zz on 2018/3/5 16:55.
 * 设备列表ListView适配器
 */

public class BluetoothDeviceAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<FoundDevice> devices;

    public BluetoothDeviceAdapter(Context context){
        this.context=context;
        devices=new ArrayList<>();
    }

    public ArrayList<FoundDevice> getDevices() {
        return devices;
    }

    @Override
    public int getCount() {
        return devices.size();
    }

    @Override
    public Object getItem(int position) {
        return devices.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView==null){
            convertView=View.inflate(context,R.layout.btdevicelayout,null);
            holder =new ViewHolder();
            holder.tvNumber=convertView.findViewById(R.id.tvNumber);
            holder.tvName=convertView.findViewById(R.id.tvName);
            holder.tvAddress=convertView.findViewById(R.id.tvAddress);
            holder.tvType=convertView.findViewById(R.id.tvType);
            holder.tvFirstRssi=convertView.findViewById(R.id.tvFirstRssi);
            convertView.setTag(holder);

        }else{
            holder =(ViewHolder)convertView.getTag();
        }
        holder.tvNumber.setText(String.format(Locale.getDefault(),"%02d",position+1));
        String temp="名称:"+devices.get(position).getDevice().getName();
        holder.tvName.setText(temp);
        temp="地址:"+devices.get(position).getDevice().getAddress();
        holder.tvAddress.setText(temp);
        temp="类型:";
        switch (devices.get(position).getDevice().getType()){
            case BluetoothDevice.DEVICE_TYPE_UNKNOWN:temp+="未知设备";break;
            case BluetoothDevice.DEVICE_TYPE_CLASSIC:temp+="BR/EDR设备";break;
            case BluetoothDevice.DEVICE_TYPE_LE:temp+="LE设备";break;
            case BluetoothDevice.DEVICE_TYPE_DUAL:temp+="双模设备";break;
        }
        holder.tvType.setText(temp);
        holder.tvFirstRssi.setText(String.format(Locale.getDefault(),"发现时RSSI:%d",devices.get(position).getRSSI()));
        return convertView;
    }
    private static class ViewHolder{
        TextView tvNumber;
        TextView tvName;
        TextView tvAddress;
        TextView tvType;
        TextView tvFirstRssi;

    }
}
